import nwbuild from "nw-builder";
import fs from 'fs-extra'
import {execSync} from "node:child_process";

let platform = getArg('platform')
let outDir, arch
if ('win64' === platform) {
  outDir = './out/win64'
  platform = 'win'
  arch = 'x64'
} else if ('osx64' === platform) {
  outDir = './out/osx64'
  platform = 'osx'
  arch = 'x64'
} else {
  console.error('platform不匹配!');
  process.exit(1);
}

execSync('yarn --cwd ../ run build')

if (fs.pathExistsSync(outDir)) fs.removeSync(outDir)
if (fs.pathExistsSync('./temp')) fs.removeSync('./temp')
fs.copySync('../dist/demo-nwjs5', './temp')
fs.copySync('./package-prod.json', './temp/package.json')

nwbuild({
  srcDir: "./temp",
  mode: "build", // "run" | "build"
  version: "0.81.0",
  flavor: "normal", // "normal" | "sdk"
  platform: platform, // "linux" | "osx" | "win"
  arch: arch, // "ia32" | "x64" | "arm64"
  outDir: outDir,
  cacheDir: "./cache",
  downloadUrl: 'https://npmmirror.com/mirrors/nwjs',
  glob: false,
  logLevel: "debug",
}).then(() => fs.removeSync('./temp'));

// -------------------------
function getArg(key) {
  let args = process.argv
  let arg = args.filter(s => s.startsWith(`--${key}=`)).map(s => s.split(`--${key}=`)[1])
  if (arg && arg.length > 0) return arg[0]
  return undefined
}
